package com.app.task;

import com.app.domain.zl.ZljlData;
import com.app.domain.zl.ZljlDataUploadStatus;
import com.app.domain.zl.ZljlInfo;
import com.app.service.ZlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class ZljlDataUploadTask {

    @Autowired
    private ZlService zlService;

    @Value("${zl.shebeibianhao}")
    private String shebeibianhao;

    /**
     * 每分钟执行一次扫描任务
     * 检查未上传的梁，如果存在已完成但未上传的孔，则触发上传
     */
    @Scheduled(cron = "0 * * * * ?")
    public void scanAndUploadZljlData() {
        try {
            log.info("开始执行张拉数据上传任务");

            // 查找所有未上传的梁（uploaded值为2或NULL）
            List<ZljlInfo> zljlInfoList = zlService.findZljlInfoByUploadStatus();
            log.info("找到 {} 个未上传的梁", zljlInfoList.size());

            if (zljlInfoList.isEmpty()) {
                log.info("没有需要上传的梁数据");
                return;
            }

            AtomicInteger totalUploadedHoles = new AtomicInteger(0);
            AtomicInteger totalFailedHoles = new AtomicInteger(0);

            for (ZljlInfo zljlInfo : zljlInfoList) {
                try {
                    log.info("处理梁号: {}", zljlInfo.getQlbh());

                    // 查询未上传但已完成的孔数据
                    List<ZljlData> unuploadedHoles = zlService.findUnuploadedFinishedHolesWithNewStatus(zljlInfo.getQlbh());
                    log.info("梁号 {} 找到 {} 个未上传的孔", zljlInfo.getQlbh(), unuploadedHoles.size());

                    // 如果存在已完成但未上传的孔数据，则进行上传
                    if (!unuploadedHoles.isEmpty()) {
                        // 上传每个未上传的孔数据
                        for (ZljlData zljlData : unuploadedHoles) {
                            try {
                                if (zljlData.getDing_xz().equals("B")) {
                                    // 检查是否为终阶段孔道，如果是则检查对应的初阶段孔道是否已上传
                                    if (isFinalStageHole(zljlData)) {
                                        if (!isInitialStageUploaded(zljlInfo, zljlData)) {
                                            log.warn("终阶段孔道 {} 依赖的初阶段孔道未上传，跳过上传", zljlData.getGsbh());
                                            totalFailedHoles.incrementAndGet();
                                            continue;
                                        }
                                    }
                                }

                                // 调用上传逻辑
                                boolean uploadSuccess = zlService.uploadSingleHoleData(zljlInfo, zljlData, shebeibianhao);

                                // 记录上传结果
                                if (uploadSuccess) {
                                    totalUploadedHoles.incrementAndGet();
                                    log.info("上传成功，梁号: {}，孔号: {}", zljlInfo.getQlbh(), zljlData.getGsbh());
                                } else {
                                    totalFailedHoles.incrementAndGet();
                                    log.warn("上传失败，梁号: {}，孔号: {}", zljlInfo.getQlbh(), zljlData.getGsbh());
                                }
                            } catch (Exception e) {
                                totalFailedHoles.incrementAndGet();
                                log.error("上传孔数据时发生异常，梁号: {}，孔号: {}", zljlInfo.getQlbh(), zljlData.getGsbh(), e);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("处理梁号 {} 时发生异常", zljlInfo.getQlbh(), e);
                }
            }

            log.info("张拉数据上传任务执行完成，总共上传 {} 个孔，失败 {} 个孔",
                    totalUploadedHoles.get(), totalFailedHoles.get());

        } catch (Exception e) {
            log.error("执行张拉数据上传任务时发生异常", e);
        }
    }

    /**
     * 判断是否为终阶段孔道
     *
     * @param zljlData 孔道数据
     * @return 是否为终阶段孔道
     */
    private boolean isFinalStageHole(ZljlData zljlData) {
        return zljlData.getGsbh().contains("终");
    }

    /**
     * 检查初阶段孔道是否已上传
     *
     * @param zljlInfo 梁信息
     * @param zljlData 终阶段孔道数据
     * @return 初阶段孔道是否已上传
     */
    private boolean isInitialStageUploaded(ZljlInfo zljlInfo, ZljlData zljlData) {
        try {
            // 获取初阶段孔道编号
            String initialStageHoleNumber = zljlData.getGsbh().replace("终", "初");

            // 根据梁号和初阶段孔道编号查找初阶段孔道数据
            ZljlData initialStageHole = null;
            List<ZljlData> allHoles = zlService.findZljlDataByQlbh(zljlInfo.getQlbh());
            for (ZljlData hole : allHoles) {
                if (initialStageHoleNumber.equals(hole.getGsbh())) {
                    initialStageHole = hole;
                    break;
                }
            }

            // 如果找不到初阶段孔道数据，则返回false
            if (initialStageHole == null) {
                log.warn("未找到初阶段孔道数据，梁号: {}，孔号: {}", zljlInfo.getQlbh(), initialStageHoleNumber);
                return false;
            }

            // 检查初阶段孔道是否已上传
            ZljlDataUploadStatus status = zlService.findZljlDataUploadStatusByZljlDataId(initialStageHole.getId());
            return status != null && "1".equals(status.getUploadedFlag());
        } catch (Exception e) {
            log.error("检查初阶段孔道上传状态时发生异常，梁号: {}，终阶段孔号: {}", zljlInfo.getQlbh(), zljlData.getGsbh(), e);
            return false;
        }
    }
}